import java.util.HashMap;
import java.util.Map;

/**
 * Created With IntelliJ IDEA
 * Description:leetcode:219. 存在重复元素 II
 * <a href="https://leetcode.cn/problems/contains-duplicate-ii/">...</a>
 * User: DELL
 * Data: 2023-03-05
 * Time: 0:04
 */
public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if (k <= 0) {
            return false;
        }
        Map<Integer,Integer> hashMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (!hashMap.containsKey(nums[i])) {
                hashMap.put(nums[i],i);
            } else {
                int index = hashMap.get(nums[i]);
                if (i - index <= k) {
                    return true;
                } else {
                    hashMap.put(nums[i],i);
                }
            }
        }
        return false;
    }
}